<template>
  <div class="upload-container">
    <el-upload
      :show-file-list="false"
      action="/"
      :headers="headers"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :http-request="httpRequest"
      :disabled="imgDisabled || isLoading"
      drag
    >
      <el-image
        v-if="value === ''"
        v-loading="isLoading"
        :src="value === '' ? placeholder : value"
        :style="`width:${width}px;height:${height}px;`"
        fit="fill"
      >
        <div slot="error" class="image-slot">
          <i class="el-icon-plus" />
        </div>
      </el-image>
      <div v-else v-loading="isLoading" class="image">
        <el-image
          :src="value"
          :style="`width:${width}px;height:${height}px;`"
          fit="fill"
        />
        <div class="mask">
          <div class="actions">
            <span title="预览" @click.stop="dialogVisible = true">
              <i class="el-icon-zoom-in" />
            </span>
            <span title="移除" @click.stop="remove">
              <i class="el-icon-delete" />
            </span>
          </div>
        </div>
      </div>
    </el-upload>
    <div v-if="!notip" class="el-upload__tip">
      <div style="display: inline-block;">
        <span slot="title">
          {{
            uploadTips
              ? uploadTips
              : `上传图片支持 ${uploadType.join(
                ' / '
              )} 格式，且图片大小不超过 ${size /
                1024}MB，建议图片尺寸为 ${width}*${height}`
          }}</span>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="预览" width="800px">
      <img
        :src="value"
        style="display: block; max-width: 100%; margin: 0 auto;"
      >
    </el-dialog>
  </div>
</template>

<script>
import ImgUploadMixin from '../mixins/ImgUploadFn'
import { upload } from 'dependencies/api/index'
import SectionLoadingMixin from 'modules/mixins/section-loading'
export default {
  name: 'ImageUpload',
  mixins: [ImgUploadMixin, SectionLoadingMixin],
  props: {
    headers: {
      type: Object,
      default: () => {}
    },
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    notip: {
      type: Boolean,
      default: false
    },
    uploadType: {
      type: Array,
      default: () => ['jpg', 'jpeg', 'png', 'gif']
    },
    imgWidth: {
      type: Number,
      default: 150
    },
    imgHeight: {
      type: Number,
      default: 150
    },
    imgDisabled: Boolean
  },
  data() {
    return {
      dialogVisible: false
    }
  },
  computed: {
    width() {
      return this.imgWidth || this.uploadWidth
    },
    height() {
      return this.imgHeight || this.uploadHeight
    }
  },
  methods: {
    // 移除
    remove() {
      this.$emit('update:data', '')
    },
    async beforeUpload(file) {
      let errorMsg = ''
      const typeLimit = this.typeLimit(file)
      // 类型不对后面都没有验收的必要了
      if (typeLimit) {
        this.$message.error(typeLimit)
        return Promise.reject()
      }

      const sizeLimit = this.sizeLimit(file)
      sizeLimit && (errorMsg += sizeLimit)

      const widthHeightLimit = await this.widthHeightLimit(file)
      widthHeightLimit && (errorMsg += widthHeightLimit)

      // 自定义事件一定要在获取宽高之后
      const validateMsg = this.customLimit(file)
      validateMsg && (errorMsg += validateMsg)

      if (errorMsg) {
        this.$message.error(errorMsg)
        return Promise.reject()
      }
      return true
    },
    onSuccess(res, file) {
      if (res) {
        this.$message.success('上传成功!')
        this.imageUrl = res.url || this.createImgUrl(file.raw)
        this.currentFile = file
        this.$emit('success', this.imageUrl)
        this.$emit('input', this.imageUrl)
      }
    },
    async httpRequest(data) {
      this.loading()
      try {
        // 上传到云存储
        let uploadRes = await vk.uploadFile({
          file: data.file
        });
        if (uploadRes) {
          return uploadRes
        } else {
          this.handleError()
        }
      } finally {
        this.loaded()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  line-height: initial;
}
.image {
  position: relative;
  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    font-size: 24px;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
    .actions {
      width: 100px;
      height: 100px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      position: absolute;
      justify-content: center;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%);
      span {
        width: 50%;
        text-align: center;
        color: #fff;
        cursor: pointer;
        transition: all 0.1s;
        &.disabled {
          color: #999;
          cursor: not-allowed;
        }
        &:hover:not(.disabled) {
          transform: scale(1.5);
        }
      }
    }
  }
  &:hover .mask {
    opacity: 1;
  }
}
::v-deep .el-upload {
  width: auto;
  .el-upload-dragger {
    width: auto;
    height: auto;
    &.is-dragover {
      border-width: 1px;
    }
    .el-image {
      display: block;
      .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        color: #909399;
        font-size: 30px;
        background-color: transparent;
      }
    }
    .progress {
      position: absolute;
      top: 0;
      &::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        background-color: rgba(0, 0, 0, 0.2);
      }
      .el-progress {
        z-index: 1;
        left: 50%;
        top: 50%;
        position: absolute;
        transform: translateX(-50%) translateY(-50%);
        .el-progress__text {
          color: #fff;
        }
      }
    }
  }
}
</style>
